


/**
 * 生成UUID
 * @param len 生成的位数，默认32位
 * @param radix 进制
 * @returns 返回UUID字符串，例如：5e71b6a38364c189ab1229bf5c2d5695
 */
export const getUUID = (len = 32, radix = 16, firstU = true,) => {
  const CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
  const uuid = []
  let i
  radix = radix || CHARS.length
  if (len) {
    for (i = 0; i < len; i++) uuid[i] = CHARS[0 | (Math.random() * radix)]
  } else {
    let r
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
    uuid[14] = '4'
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16)
        uuid[i] = CHARS[i == 19 ? (r & 0x3) | 0x8 : r]
      }
    }
  }
  // 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class
  if (firstU) {
    uuid.shift()
    return `u${uuid.join('')}`
  }
  return uuid.join('')
}

/**
 * 生成GUID
 * @returns 返回GUID字符串，例如：e854e2ec-063c-1ee7-942f-57c5733ce0cb
 */
export const getGUID = () => {
  const s4 = function () {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
  }
  return (
    s4() +
    s4() +
    '-' +
    s4() +
    '-' +
    s4() +
    '-' +
    s4() +
    '-' +
    s4() +
    s4() +
    s4()
  )
}

/**
 * 判断 移动端 OR PC端
 * @returns 
 */
export const isMobile = () => {
  let plat = navigator.userAgent.match( // 判断不同端
    /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
  );
  return plat;
}

/**
 * 数组转树形数据
 * @param {Object} list 原数组数据
 * @param {String|Number} rootId 根节点ID，默认 '0'
 * @param {String} idName 节点id字段名称
 * @param {String} pidName 父节点id字段名称，默认 'pid'
 * @param {String} childrenName 子节点数组字段名称，默认 'children'
 */

export const listToTree = (list, rootId = '0', idName = 'id', pidName = 'pid', childrenName = 'children') => {
  // 返回结果
  const result = []
  // map中间存储，利用对象的浅拷贝原理进行数组的拼装
  const map = {}

  for (const item of list) {
    const id = item[idName]
    const parentId = item[pidName]

    map[id] = {
      ...item,
      [childrenName]: map[id] && map[id][childrenName] ? map[id][childrenName] : []
    }

    const treeItem = map[id]

    if (parentId === rootId) {
      result.push(treeItem)
    } else {
      !map[parentId] && (map[parentId] = { children: [] })  // 可有可无，防止报错
      map[parentId][childrenName].push(treeItem)
    }
  }
}